from django.db import models

# Create your models here.

from django.contrib.auth.models import User
from django.utils.text import slugify
import uuid
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, Group, Permission  # 新增 Group、Permission 导入
from django.db import models
import datetime
from django.conf import settings
from django.utils import timezone


class Strategy(models.Model):
    """攻略模型，假设已存在"""
    title = models.CharField(max_length=200)
    content = models.TextField()

    # 其他字段...

    def __str__(self):
        return self.title


class Favorite(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,  # 替换为动态关联
        on_delete=models.CASCADE,
        related_name='favorites'
    )
    strategy = models.ForeignKey(Strategy, on_delete=models.CASCADE, related_name='favorited_by')
    created_at = models.DateTimeField(default=timezone.now)

    class Meta:
        unique_together = ('user', 'strategy')
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.username} 收藏了 {self.strategy.title}"  # 改为 username


# models.py
class UserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError('必须提供用户名')

        user = self.model(
            username=username,
            **extra_fields
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password=None, **extra_fields):
        extra_fields.setdefault('is_admin', True)
        return self.create_user(username, password, **extra_fields)


class CustomUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=100, unique=True, verbose_name="用户名")
    nickname = models.CharField(max_length=50, blank=True, null=True, verbose_name="昵称")
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)  # 作为字段
    is_admin = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['nickname']

    groups = models.ManyToManyField(
        Group,
        verbose_name='用户组',
        blank=True,
        related_name='xiangxi_travel_users'
    )
    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name='用户权限',
        blank=True,
        related_name='xiangxi_travel_user_perms'
    )

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return self.is_admin

    # 移除 @property is_staff 方法，因为已经有了 is_staff 字段

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户"

class Category(models.Model):
    """景点分类模型"""
    name = models.CharField(max_length=50, unique=True, verbose_name="分类名称")
    description = models.TextField(blank=True, null=True, verbose_name="分类描述")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    # 添加分类图标
    icon = models.CharField(max_length=50, blank=True, null=True, verbose_name="图标类名")

    class Meta:
        verbose_name = "景点分类"
        verbose_name_plural = "景点分类"
        ordering = ["name"]

    def __str__(self):
        return self.name


class City(models.Model):
    """城市模型"""
    name = models.CharField(max_length=50, verbose_name="城市名称")
    county = models.CharField(max_length=50, blank=True, null=True, verbose_name="县镇")
    description = models.TextField(blank=True, null=True, verbose_name="城市描述")
    # 添加城市首字母用于排序
    initial = models.CharField(max_length=1, blank=True, null=True, verbose_name="首字母")

    class Meta:
        verbose_name = "城市"
        verbose_name_plural = "城市"
        ordering = ["name"]

    def __str__(self):
        return f"{self.name}{' - ' + self.county if self.county else ''}"


class Tag(models.Model):
    """标签模型 - 新增"""
    name = models.CharField(max_length=30, unique=True, verbose_name="标签名称")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "标签"
        verbose_name_plural = "标签"
        ordering = ["name"]

    def __str__(self):
        return self.name


class Attraction(models.Model):
    """景点模型"""
    CATEGORY_CHOICES = [
        ('自然风光', '自然风光'),
        ('历史古迹', '历史古迹'),
        ('民族村寨', '民族村寨'),
        ('文化体验', '文化体验'),
        ('红色旅游', '红色旅游'),
    ]

    LEVEL_CHOICES = [
        ('A', 'A级'),
        ('AA', 'AA级'),
        ('AAA', 'AAA级'),
        ('AAAA', 'AAAA级'),
        ('AAAAA', 'AAAAA级'),
        ('无', '无'),
    ]

    name = models.CharField(max_length=100, verbose_name="景点名称")
    alias = models.CharField(max_length=200, blank=True, null=True, verbose_name="景点别名")
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, verbose_name="景点类型")
    # 增加与Category模型的关联
    category_detail = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True,
                                        related_name="attractions", verbose_name="详细分类")
    city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="attractions", verbose_name="所在城市")
    address = models.CharField(max_length=255, blank=True, null=True, verbose_name="详细地址")
    longitude = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name="经度")
    latitude = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name="纬度")
    level = models.CharField(max_length=5, choices=LEVEL_CHOICES, default="无", verbose_name="景区等级")
    ticket_price = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="门票价格")
    # 新增门票优惠信息
    ticket_discount = models.TextField(blank=True, null=True, verbose_name="门票优惠")
    opening_hours = models.CharField(max_length=255, blank=True, null=True, verbose_name="开放时间")
    description = models.TextField(blank=True, null=True, verbose_name="景点描述")
    recommend_hours = models.DecimalField(max_digits=5, decimal_places=1, blank=True, null=True,
                                          verbose_name="建议游玩时间(小时)")
    best_season = models.CharField(max_length=100, blank=True, null=True, verbose_name="最佳旅游季节")
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name="联系电话")
    parking_info = models.CharField(max_length=255, blank=True, null=True, verbose_name="停车信息")
    disabled_access = models.BooleanField(default=False, verbose_name="是否无障碍通道")
    # 新增交通信息
    transportation = models.TextField(blank=True, null=True, verbose_name="交通方式")
    # 新增评分
    rating = models.DecimalField(max_digits=3, decimal_places=1, default=0, verbose_name="评分")
    slug = models.SlugField(max_length=120, unique=True, blank=True, verbose_name="URL别名")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    # 新增标签关联
    tags = models.ManyToManyField(Tag, related_name="attractions", blank=True, verbose_name="标签")

    class Meta:
        verbose_name = "景点"
        verbose_name_plural = "景点"
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["category"]),
            models.Index(fields=["city"]),
            models.Index(fields=["rating"]),  # 新增评分索引
        ]

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name) + "-" + str(uuid.uuid4())[:8]
        super().save(*args, **kwargs)

    def __str__(self):
        return self.name


class AttractionImage(models.Model):
    """景点图片模型"""
    attraction = models.ForeignKey(Attraction, on_delete=models.CASCADE, related_name="images", verbose_name="关联景点")
    image_url = models.ImageField(upload_to="attractions/", verbose_name="图片路径")
    image_desc = models.CharField(max_length=255, blank=True, null=True, verbose_name="图片描述")
    is_cover = models.BooleanField(default=False, verbose_name="是否封面图")
    sort_order = models.IntegerField(default=0, verbose_name="排序序号")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "景点图片"
        verbose_name_plural = "景点图片"
        ordering = ["sort_order", "-created_at"]

    def __str__(self):
        return f"{self.attraction.name}的图片{'(封面)' if self.is_cover else ''}"


class TravelGuide(models.Model):
    """攻略文章模型"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('rejected', '已拒绝'),
    ]

    title = models.CharField(max_length=200, verbose_name="攻略标题")
    # 2. 确保 author 字段关联 settings.AUTH_USER_MODEL
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,  # 关键：必须是这个，不能是 User 或其他
        on_delete=models.CASCADE,
        related_name="guides",
        verbose_name="作者"
    )

    cover_image = models.ImageField(upload_to="guides/covers/", blank=True, null=True, verbose_name="封面图片")
    content = models.TextField(verbose_name="攻略内容")
    attractions = models.ManyToManyField(Attraction, related_name="guides", blank=True, verbose_name="关联景点")
    # 新增行程天数
    days = models.IntegerField(default=1, blank=True, null=True, verbose_name="行程天数")
    # 新增人均费用
    avg_cost = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name="人均费用")
    read_count = models.IntegerField(default=0, verbose_name="阅读量")
    collect_count = models.IntegerField(default=0, verbose_name="收藏数")
    comment_count = models.IntegerField(default=0, verbose_name="评论数")
    # 新增点赞数
    like_count = models.IntegerField(default=0, verbose_name="点赞数")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="draft", verbose_name="状态")
    is_recommended = models.BooleanField(default=False, verbose_name="是否推荐")
    # 新增标签关联
    tags = models.ManyToManyField(Tag, related_name="guides", blank=True, verbose_name="标签")
    slug = models.SlugField(max_length=220, unique=True, blank=True, verbose_name="URL别名")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "旅游攻略"
        verbose_name_plural = "旅游攻略"
        ordering = ["-created_at"]

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title) + "-" + str(uuid.uuid4())[:8]
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title


class Comment(models.Model):
    """评论模型"""
    guide = models.ForeignKey(TravelGuide, on_delete=models.CASCADE, related_name="comments", verbose_name="关联攻略")
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="comments", verbose_name="评论用户")
    content = models.TextField(verbose_name="评论内容")
    # 修复自关联问题：使用'self'引用当前模型
    parent = models.ForeignKey(
        'self',  # 关键点：使用'self'替代'Comment'
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name="replies",
        verbose_name="父评论"
    )
    like_count = models.IntegerField(default=0, verbose_name="点赞数")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="评论时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "评论"
        verbose_name_plural = "评论"
        ordering = ["created_at"]

    def __str__(self):
        return f"{self.user.username} 评论了 {self.guide.title}"  # 改为 username



class Collection(models.Model):
    """收藏模型"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,  # 替换为动态关联
        on_delete=models.CASCADE,
        related_name="collections",
        verbose_name="用户"
    )
    guide = models.ForeignKey(TravelGuide, on_delete=models.CASCADE, related_name="collections", verbose_name="攻略")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="收藏时间")

    class Meta:
        verbose_name = "收藏"
        verbose_name_plural = "收藏"
        unique_together = ["user", "guide"]  # 一个用户只能收藏一次同一篇攻略
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.user.username} 收藏了 {self.guide.title}"  # 改为 username


class TravelTip(models.Model):
    """旅游小贴士模型"""
    title = models.CharField(max_length=100, verbose_name="标题")
    content = models.TextField(verbose_name="内容")
    category = models.CharField(max_length=50, blank=True, null=True, verbose_name="分类")
    # 关联相关城市
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True, blank=True,
                             related_name="tips", verbose_name="相关城市")
    is_recommended = models.BooleanField(default=False, verbose_name="是否推荐")
    # 新增浏览量
    view_count = models.IntegerField(default=0, verbose_name="浏览量")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "旅游小贴士"
        verbose_name_plural = "旅游小贴士"
        ordering = ["-created_at"]

    def __str__(self):
        return self.title


class UserProfile(models.Model):
    """用户资料扩展模型 - 新增"""
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,  # 替换为动态关联
        on_delete=models.CASCADE,
        related_name="profile",
        verbose_name="用户"
    )
    avatar = models.ImageField(upload_to="avatars/", blank=True, null=True, verbose_name="头像")
    bio = models.TextField(blank=True, null=True, verbose_name="个人简介")
    # 常用旅游城市
    favorite_city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True, blank=True,
                                      verbose_name="常用旅游城市")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "用户资料"
        verbose_name_plural = "用户资料"

    def __str__(self):
        return f"{self.user.username}的资料"


class Itinerary(models.Model):
    """行程计划模型 - 新增"""
    STATUS_CHOICES = [
        ('planning', '规划中'),
        ('confirmed', '已确认'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]

    title = models.CharField(max_length=200, verbose_name="行程标题")
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,  # 替换为动态关联
        on_delete=models.CASCADE,
        related_name="itineraries",
        verbose_name="用户"
    )
    start_date = models.DateField(verbose_name="开始日期")
    end_date = models.DateField(verbose_name="结束日期")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="planning", verbose_name="状态")
    # 关联景点
    attractions = models.ManyToManyField(Attraction, related_name="itineraries", blank=True, verbose_name="行程景点")
    notes = models.TextField(blank=True, null=True, verbose_name="行程备注")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "行程计划"
        verbose_name_plural = "行程计划"
        ordering = ["-created_at"]

    def __str__(self):
        return self.title
